package com.example.ycdyus.dailyfruit.adapter;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.ycdyus.dailyfruit.BaseApp;
import com.example.ycdyus.dailyfruit.R;
import com.example.ycdyus.dailyfruit.bean.Products;
import com.example.ycdyus.dailyfruit.bean.QiangxianBean;
import com.example.ycdyus.dailyfruit.db.Good;
import com.example.ycdyus.dailyfruit.utils.ImageLoaderHelper;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.List;

/**
 * Created by ycdyus on 2015/10/25.
 */
public class QiangxianAdapter extends CommonAdapter<Products>{
    private DisplayImageOptions options;

    public QiangxianAdapter(Context context, List<Products> mDatas, int itemLayoutId) {
        super(context, mDatas, itemLayoutId);
        options = ImageLoaderHelper.getDisplayImageLoader();
    }

    @Override
    public void convert(ViewHolders holder, final Products item) {
        ImageLoader.getInstance().displayImage(item.getPhoto(), (ImageView) holder.getView(R.id.iv_item_qiangxian_img), options);
        ((TextView)holder.getView(R.id.tv_item_qiangxian_product_name)).setText(item.getProduct_name());
        ((TextView)holder.getView(R.id.tv_item_qiangxian_volume)).setText(item.getVolume());
        ((TextView)holder.getView(R.id.tv_item_qiangxian_price)).setText(item.getPrice());
        ((TextView)holder.getView(R.id.tv_item_qiangxian_old_price)).setText("￥" + item.getOld_price());
        ((TextView)holder.getView(R.id.tv_item_qiangxian_volume)).setText(item.getVolume());
        ((Button)holder.getView(R.id.tv_item_qiangcian_add)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Good good = new Good();
                good.setName(item.getProduct_name());
                good.setProduct_id(item.getId());
                good.setSpec(item.getVolume());
                good.setSale_price(item.getPrice());
                good.setPhotos(item.getPhoto());
                good.setNum(1);
                try {
                    if(BaseApp.getInstance().getDbUtils().findFirst(Selector.from(Good.class).where("name", "=", item.getProduct_name()))==null){
                        BaseApp.getInstance().getDbUtils().save(good);
                        BaseApp.showToast("加入购物车成功");
                    }else{
                        BaseApp.showToast("已存在购物车");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
